<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="平台项目阶段" data-page-identification="x_zugnuq856n">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_7vqxc7rhzg 自定义模板_y7xb4613m4 -->
            <!--            新建/编辑用户故事-->
            <a-modal
                :visible="milepostState.addOrEditVisible"
                :title="milepostState.addOrEditTitle"
                centered
                :mask-closable="false"
                destroy-on-close
                :body-style="{
                    maxHeight: '800px',
                    overflowY: 'auto'
                }"
                width="1000px"
                @cancel="cancelStory"
            >
                <template #footer>
                    <a-button type="primary" @click="cancleMbTask"> 取消</a-button>
                    <a-button
                        type="primary"
                        v-if="
                            milepostState.current == 1 &&
                            milepostState.modalForm.templateTaskId?.length > 0 &&
                            !currentData.id
                        "
                        @click="getTask"
                        :loading="milepostState.nextLoading"
                    >
                        下一步</a-button
                    >
                    <a-button type="primary" v-if="milepostState.current == 2" @click="milepostState.current = 1">
                        上一步</a-button
                    >
                    <a-button
                        type="primary"
                        @click="confirmMbTask"
                        v-if="
                            milepostState.current == 2 ||
                            (milepostState.modalForm.templateTaskId?.length == 0 && milepostState.current == 1)
                        "
                        :loading="milepostState.okLoading"
                    >
                        确定</a-button
                    >
                </template>
                <div class="form-model">
                    <a-form :model="milepostState.modalForm" ref="formRef" :rules="rules">
                        <a-row v-if="milepostState.current == 1">
                            <a-col :span="24">
                                <a-form-item label="用户故事名称" name="storyName">
                                    <a-input
                                        v-model:value="milepostState.modalForm.storyName"
                                        :placeholder="inputHolder"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="计划起止时间">
                                    <a-range-picker
                                        style="width: 100%"
                                        v-model:value="milepostState.modalForm.timeRangeList"
                                        valueFormat="YYYY-MM-DD"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item
                                    label="优先级"
                                    name="priority"
                                    :rules="[{ required: true, validator: validatePriority, trigger: 'blur' }]"
                                >
                                    <a-input-number
                                        style="width: 100%"
                                        placeholder="请输入 1 到 99 之间，最多一位小数的正数"
                                        v-model:value="milepostState.modalForm.priority"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="标签" name="labels">
                                    <a-input
                                        v-model:value="milepostState.modalForm.labels"
                                        show-count
                                        :placeholder="inputHolder"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24" v-if="!currentData.id">
                                <a-form-item
                                    label="功能简称"
                                    name="functionAbbreviation"
                                    :rules="[
                                        {
                                            required: milepostState.modalForm.templateTaskId.length>0 ? true : false,
                                            message: '请输入功能简称',
                                            trigger: 'blur'
                                        }
                                    ]"
                                >
                                    <a-input
                                        :placeholder="inputHolder"
                                        v-model:value="milepostState.modalForm.functionAbbreviation"
                                        maxlength="10"
                                        show-count
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24" v-if="!currentData.id">
                                <a-form-item label="SOP任务">
                                    <a-tree-select
                                        v-model:value="milepostState.modalForm.templateTaskId"
                                        show-search
                                        multiple
                                        treeCheckable
                                        style="width: 100%"
                                        placeholder="请选择"
                                        allow-clear
                                        treeDefaultExpandAll
                                        :tree-data="milepostState.treeData"
                                        :fieldNames="{
                                            children: 'children',
                                            label: 'taskName',
                                            value: 'taskId',
                                            key: 'taskId'
                                        }"
                                        :filterTreeNode="
                                            (inputValue, treeNode) => {
                                                return (
                                                    treeNode.taskName.toLowerCase().indexOf(inputValue.toLowerCase()) >=
                                                    0
                                                )
                                            }
                                        "
                                        :max-tag-count="7"
                                        @focus="getTreeData"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <div v-else>
                            <div
                                v-for="(item, index) in milepostState.modalForm.taskList"
                                :key="index"
                                class="form-item"
                            >
                                <div class="form-content">
                                    <a-row class="one-line">
                                        <a-col :span="24">
                                            <a-form-item
                                                label="任务名称"
                                                :name="['taskList', index, 'taskName']"
                                                :rules="[
                                                    {
                                                        required: true,
                                                        message: '请输入任务名称!'
                                                    },
                                                    {
                                                        validator: () => {
                                                            if (milepostState.modalForm.taskList[index].taskName) {
                                                                if (
                                                                    milepostState.modalForm.taskList[
                                                                        index
                                                                    ].taskName.trim()
                                                                ) {
                                                                    return PromiseProxy.resolve()
                                                                } else {
                                                                    return PromiseProxy.reject('请输入任务名称!')
                                                                }
                                                            } else {
                                                                return PromiseProxy.resolve()
                                                            }
                                                        }
                                                    }
                                                ]"
                                            >
                                                <a-input
                                                    disabled
                                                    :placeholder="inputHolder"
                                                    v-model:value="milepostState.modalForm.taskList[index].taskName"
                                                />
                                            </a-form-item>
                                        </a-col>
                                    </a-row>

                                    <a-row>
                                        <a-col :span="12">
                                            <a-form-item
                                                label="预计投入工时"
                                                :name="['taskList', index, 'workingHours']"
                                                :rules="[
                                                    { required: true, message: '请输入预计投入工时!', trigger: 'blur' },
                                                    {
                                                        pattern: /^(0\.5|[1-9](\d*)?(\.5)?(\.0)?)$/,
                                                        message: '请输入大于0的数字(支持0.5的倍数)',
                                                        trigger: 'blur'
                                                    }
                                                ]"
                                            >
                                                <a-input
                                                    placeholder="请输入工时(支持0.5的数字)"
                                                    v-model:value="milepostState.modalForm.taskList[index].workingHours"
                                                    :min="0"
                                                    type="number"
                                                    suffix="小时"
                                                />
                                            </a-form-item>
                                        </a-col>
                                        <a-col :span="12">
                                            <a-form-item
                                                label="任务起止时间"
                                                :name="['taskList', index, 'allTime']"
                                                :rules="{ required: true, message: '请选择任务起止时间!' }"
                                            >
                                                <a-range-picker
                                                    style="width: 100%"
                                                    v-model:value="milepostState.modalForm.taskList[index].allTime"
                                                    valueFormat="YYYY-MM-DD"
                                                />
                                            </a-form-item>
                                        </a-col>
                                    </a-row>
                                    <a-row>
                                        <a-col :span="12">
                                            <a-form-item
                                                label="任务负责人"
                                                :name="['taskList', index, 'taskOwner']"
                                                :rules="{ required: true, message: '请选择任务负责人!' }"
                                            >
                                                <a-select
                                                    :placeholder="selectHolder"
                                                    v-model:value="milepostState.modalForm.taskList[index].taskOwner"
                                                    showSearch
                                                    :options="peopleList"
                                                    :field-names="{ label: 'label', value: 'value' }"
                                                    :filter-option="
                                                        (input, option) => {
                                                            return (
                                                                option.label
                                                                    .toLowerCase()
                                                                    .indexOf(input.toLowerCase()) >= 0
                                                            )
                                                        }
                                                    "
                                                />
                                            </a-form-item>
                                        </a-col>
                                        <a-col :span="12">
                                            <a-form-item
                                                label="审核员"
                                                :name="['taskList', index, 'assessorName']"
                                                :rules="{ required: true, message: '请选择审核员!' }"
                                            >
                                                <a-select
                                                    :placeholder="selectHolder"
                                                    v-model:value="milepostState.modalForm.taskList[index].assessorName"
                                                    showSearch
                                                    :options="peopleList"
                                                    :field-names="{ label: 'label', value: 'value' }"
                                                    :filter-option="
                                                        (input, option) => {
                                                            return (
                                                                option.label
                                                                    .toLowerCase()
                                                                    .indexOf(input.toLowerCase()) >= 0
                                                            )
                                                        }
                                                    "
                                                />
                                            </a-form-item>
                                        </a-col>
                                    </a-row>
                                    <a-row class="one-line">
                                        <a-col :span="24">
                                            <a-form-item
                                                label="任务执行人"
                                                :name="['taskList', index, 'taskParticipantList']"
                                                :rules="{ required: true, message: '请选择任务参与人!' }"
                                            >
                                                <a-select
                                                    :placeholder="selectHolder"
                                                    v-model:value="
                                                        milepostState.modalForm.taskList[index].taskParticipantList
                                                    "
                                                    showSearch
                                                    mode="multiple"
                                                    :options="peopleList"
                                                    :field-names="{ label: 'label', value: 'value' }"
                                                    :filter-option="
                                                        (input, option) => {
                                                            return (
                                                                option.label
                                                                    .toLowerCase()
                                                                    .indexOf(input.toLowerCase()) >= 0
                                                            )
                                                        }
                                                    "
                                                />
                                            </a-form-item>
                                        </a-col>
                                    </a-row>
                                    <a-row>
                                        <a-col v-if="taskPeopleList.length > 0">
                                            <div style="width: 700px; margin-left: 115px; margin-bottom: 28px">
                                                <a
                                                    href="javascript:;"
                                                    v-for="(item, num) in taskPeopleList"
                                                    @click="handlerAddPtMbPeople(item.value, index)"
                                                    ><span style="margin: 0 5px">{{ item.value }}</span></a
                                                >
                                            </div>
                                        </a-col>
                                    </a-row>
                                    <a-row class="one-line">
                                        <a-col :span="24">
                                            <a-form-item label="备注">
                                                <a-textarea
                                                    v-model:value="milepostState.modalForm.taskList[index].remark"
                                                />
                                            </a-form-item>
                                        </a-col>
                                    </a-row>
                                </div>
                            </div>
                        </div>
                    </a-form>
                </div>
            </a-modal>
            <!--            新建/编辑用户故事-->
            <div class="body">
                <div class="top-search">
                    <a-row :gutter="24">
                        <a-col :span="6" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                            <a-form-item label="关键字">
                                <a-input
                                    v-model:value="milepostState.searchForm.keywords"
                                    @change="debounceGetData"
                                    :placeholder="inputHolder"
                                />
                            </a-form-item>
                        </a-col>

                        <a-col :span="6" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                            <a-form-item label="状态">
                                <a-select
                                    :placeholder="selectHolder"
                                    allow-clear
                                    v-model:value="milepostState.searchForm.storyStatus"
                                    :options="milepostState.statusList"
                                    @change="getData"
                                    :field-names="{
                                        label: 'label',
                                        value: 'label'
                                    }"
                                    :showSearch="true"
                                    :filterOption="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="任务排序" style="margin: 0">
                                <a-select
                                    :placeholder="selectHolder"
                                    :options="milepostState.sortList"
                                    v-model:value="milepostState.searchForm.directionField"
                                    @change="getData"
                                    allow-clear
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="3">
                            <a-space>
                                <a-button @click="resetData" ghost type="primary">重置</a-button>
                            </a-space>
                        </a-col>

                        <a-col :span="3" style="display: flex; justify-content: end; align-items: start">
                            <a-space>
                                <a-button @click="handleAdd" type="primary">新建</a-button>
                            </a-space>
                        </a-col>
                    </a-row>
                </div>
                <a-spin :spinning="milepostState.dataLoading" tip="加载中">
                    <div class="content">
                        <div class="no-progress" v-if="milepostState.dataList.length == 0">
                            <div class="tip">
                                <p class="message">暂无数据</p>
                            </div>
                        </div>
                        <div class="story-item" v-for="(item, index) in milepostState.dataList" :key="item.id">
                            <div class="story-title">
                                <div class="title-left">
                                    <div class="priority-tag" title="优先级" v-if="item.priority">{{
                                        item.priority
                                    }}</div>
                                    <div
                                        title="用户故事状态"
                                        class="status-tag"
                                        :style="{
                                            backgroundColor: getStatusColor(item.storyStatus)
                                        }"
                                        >{{ item.storyStatus }}</div
                                    >

                                    <div>{{ item.storyName }}</div>
                                </div>
                                <div class="title-right">
                                    <a-space>
                                        <a-button size="small" type="primary" ghost @click="handleEditStory(item)"
                                            >编辑</a-button
                                        >
                                        <a-popconfirm
                                            title="确定删除?"
                                            ok-text="确定"
                                            cancel-text="取消"
                                            @confirm="confirmDelete(item.id)"
                                            @cancel="cancel"
                                        >
                                            <a-button size="small" type="primary" ghost>删除</a-button>
                                        </a-popconfirm>
                                    </a-space>
                                </div>
                            </div>
                            <div class="story-content">
                                <div class="item-icon" v-if="item.labels">
                                    <div v-for="(tag, index) in handlerGetSpace(item.labels)" class="label-item">
                                        <div class="label-img"></div>{{ tag }}
                                    </div>
                                </div>
                                <!-- 第一行 -->
                                <div class="one-line">
                                    <div class="row-item">
                                        <div class="item-title">创建人：</div>
                                        <div class="item-content" :title="item.createdBy">{{ item.createdBy }}</div>
                                    </div>
                                    <div class="row-item">
                                        <div class="item-title">创建时间：</div>
                                        <div class="item-content" :title="item.createdTime">{{ item.createdTime }}</div>
                                    </div>
                                    <div class="row-item">
                                        <div class="item-title">计划开始：</div>
                                        <div class="item-content" :title="item.startTime">{{ item.startTime }}</div>
                                    </div>
                                    <div class="row-item">
                                        <div class="item-title">实际开始：</div>
                                        <div class="item-content" :title="item.actualStartTime">{{
                                            item.actualStartTime
                                        }}</div>
                                    </div>
                                    <div class="row-item">
                                        <div class="item-title">计划完成：</div>
                                        <div class="item-content" :title="item.endTime">{{ item.endTime }}</div>
                                    </div>
                                    <div class="row-item">
                                        <div class="item-title">实际完成：</div>
                                        <div class="item-content" :title="item.actualEndTime">{{
                                            item.actualEndTime
                                        }}</div>
                                    </div>
                                </div>

                                <div class="two-line">
                                    <!-- 第二行 -->
                                    <div class="row-item">
                                        <div class="item-title">SOP任务数：</div>
                                        <div class="item-content" :title="item.sopTaskNumber">{{
                                            item.sopTaskNumber
                                        }}</div>
                                    </div>
                                    <div class="row-item">
                                        <div class="item-title">进行中的SOP任务：</div>
                                        <div class="item-content" :title="item.runningSopTaskNumber">{{
                                            item.runningSopTaskNumber
                                        }}</div>
                                    </div>
                                    <div class="row-item">
                                        <div class="item-title">子任务数：</div>
                                        <div class="item-content" :title="item.otherTaskNumber">{{
                                            item.otherTaskNumber
                                        }}</div>
                                    </div>
                                    <div class="row-item">
                                        <div class="item-title">进行中的子任务：</div>
                                        <div class="item-content" :title="item.runningOtherTaskNumber">{{
                                            item.runningOtherTaskNumber
                                        }}</div>
                                    </div>
                                    <div class="row-item">
                                        <div class="item-title">问题任务数：</div>
                                        <div class="item-content" :title="item.problemNumber">{{
                                            item.problemNumber
                                        }}</div>
                                    </div>
                                    <div class="row-item">
                                        <div class="item-title">进行中的问题任务：</div>
                                        <div class="item-content" :title="item.runningProblemNumber">{{
                                            item.runningProblemNumber
                                        }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </a-spin>
            </div>
            <!-- end vid_7vqxc7rhzg 自定义模板_y7xb4613m4 -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        },
        'projectId': {
            type: [String, Number],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    const { projectId } = props
    const useProjectId = ref()
    import { watchEffect } from 'vue'
    watchEffect(() => {
        if (props.projectId) {
            setTimeout(() => {
                useProjectId.value = props.projectId
                getTemplateCode()
                getPopleList()
                getAllJfPeople()
                getData()
                getStatusList()
                console.log('项目阶段')
            }, 500)
        }
    })
    const inputHolder = '请输入'
    const selectHolder = '请选择'
    const milepostState = reactive({
        searchForm: {
            storyStatus: undefined,
            keywords: undefined,
            directionField: 'created_time-desc'
        },
        sortList: [
            {
                label: '创建时间正序',
                value: 'created_time-asc'
            },
            {
                label: '创建时间倒序',
                value: 'created_time-desc'
            },
            {
                label: '计划完成时间正序',
                value: 'end_time-asc'
            },
            {
                label: '计划完成时间倒序',
                value: 'end_time-desc'
            },
            {
                label: '计划开始时间正序',
                value: 'start_time-asc'
            },
            {
                label: '计划开始时间倒序',
                value: 'start_time-desc'
            },
            {
                label: '优先级正序',
                value: 'priority-asc'
            },
            {
                label: '优先级倒序',
                value: 'priority-desc'
            }
        ],
        dataList: [],
        treeData: [],
        targetKeys: [],
        selectKeys: [],
        SopTaskList: [],
        addOrEditVisible: false,
        dataLoading: false,
        nextLoading: false,
        okLoading: false,
        addOrEditTitle: '',
        modalForm: {
            storyName: undefined,
            priority: undefined,
            labels: undefined,
            timeRangeList: [],
            taskList: [],
            templateTaskId: []
        },
        current: 1,
        statusList: []
    })
    const validatePriority = (rule, value) => {
        if (value === undefined || value === null || value === '') {
            return Promise.reject(new Error('请输入优先级'))
        }
        const number = Number(value)
        const isValid = number > 0 && number < 100 && /^(\d{1,2})(\.\d)?$/.test(value.toString())
        return isValid ? Promise.resolve() : Promise.reject(new Error('请输入 1 到 99 之间，最多一位小数的正数'))
    }
    const formRef = ref(null)
    const rules = {
        storyName: [
            {
                required: true,
                message: '请输入用户故事名称',
                trigger: 'blur'
            }
        ],
        allTime: [{ required: false, message: '请选择任务起止时间!', trigger: 'blur' }]
        // functionAbbreviation: [{ required: true, message: '请输入功能简称', trigger: 'blur' }]
    }
    const currentData = ref({})
    // 新建弹窗
    function handleAdd() {
        milepostState.addOrEditVisible = true
        milepostState.addOrEditTitle = '新建用户故事'
        currentData.value = {}
    }
    // 获取列表
    function getData() {
        milepostState.dataLoading = true
        post('/solution-ppm/api/v2/built-in-system-ppm/project/story/search', {
            projectId: useProjectId.value,
            ...milepostState.searchForm
        })
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    milepostState.dataList = []
                    return
                }
                milepostState.dataList = data.data
            })
            .finally(() => {
                milepostState.dataLoading = false
            })
    }
    // 重置
    function resetData() {
        milepostState.searchForm.storyStatus = milepostState.searchForm.keywords = undefined
        milepostState.searchForm.directionField = 'created_time-desc'
        getData()
    }
    //     新建下一步获取任务
    function getTask() {
        formRef.value.validate().then(() => {
            milepostState.nextLoading = true
            post('/solution-ppm/api/v2/built-in-system-ppm/v2/platform/generate_task', {
                templateTaskId: milepostState.modalForm.templateTaskId,
                storyId: milepostState.modalForm.storyId,
                functionAbbreviation: milepostState.modalForm.functionAbbreviation,
                projectId: useProjectId.value
            })
                .then(data => {
                    milepostState.current = 2
                    milepostState.modalForm.taskList = data.data.map(item => {
                        return {
                            ...item,
                            allTime: [item.startTime, item.endTime]
                        }
                    })
                })
                .finally(() => {
                    milepostState.nextLoading = false
                })
        })
    }
    const taskPeopleList = ref([])
    function getPopleList() {
        post(`/solution-ppm/api/v2/built-in-system-ppm/task/getTopUser/${useProjectId.value}`).then(data => {
            taskPeopleList.value = data.data.map(item => {
                return {
                    label: item,
                    value: item
                }
            })
        })
    }
    const peopleList = ref([])
    function getAllJfPeople() {
        get('/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/allUser').then(({ data }) => {
            peopleList.value = data.userDtoList.map(item => {
                return {
                    label: item.name,
                    value: item.name
                }
            })
        })
    }
    // 快捷添加执行人
    function handlerAddPtMbPeople(name, index) {
        if (milepostState.modalForm.taskList[index].taskParticipantList.indexOf(name) !== -1) {
            milepostState.modalForm.taskList[index].taskParticipantList = milepostState.modalForm.taskList[
                index
            ].taskParticipantList.filter(item => item !== name)
        } else {
            milepostState.modalForm.taskList[index].taskParticipantList.push(name)
        }
    }
    function cancelStory() {
        currentData.value = {}
        milepostState.addOrEditVisible = false
        milepostState.modalForm = {
            storyName: undefined,
            timeRangeList: [],
            taskList: [],
            templateTaskId: []
        }
    }
    const colorMap = {
        '进行中': '#3875FF',
        '完成': '#52C41A',
        '未启动': '#8C8C8C',
        '未开始': '#8C8C8C',
        '已完成': '#52C41A'
    }
    function getStatusColor(status) {
        return colorMap[status] || '#8C8C8C'
    }
    function getPriorityColor(priority) {}
    const projectTemplate = ref()
    function getTemplateCode() {
        get(`/solution-ppm/api/v2/built-in-system-ppm/project/${useProjectId.value}`).then(data => {
            projectTemplate.value = data.projectTemplate
        })
    }

    //     获取穿梭框
    function getTreeData() {
        get(
            `/solution-ppm/api/v2/built-in-system-ppm/v2/platform/template_milepost_task?templateCode=${projectTemplate.value}&functionAbbreviation=${milepostState.modalForm.functionAbbreviation}&projectId=${useProjectId.value}`
        ).then(data => {
            milepostState.treeData = data.data
            // flatten(JSON.parse(JSON.stringify(milepostState.treeData)))
            console.log(milepostState.treeData)
            milepostState.modalForm.selectKeys = []
        })
    }
    // 保存模板项目
    function confirmMbTask() {
        formRef.value.validate().then(() => {
            milepostState.okLoading = true
            milepostState.modalForm.taskList.forEach(item => {
                item.startTime = item.allTime[0]
                item.endTime = item.allTime[1]
            })
            const api = currentData.value.id ? put : post

            api(`/solution-ppm/api/v2/built-in-system-ppm/project/story`, {
                projectId: useProjectId.value,
                timeRangeList: milepostState.modalForm.timeRangeList,
                storyName: milepostState.modalForm.storyName,
                ppmPlatformTaskFormList: milepostState.modalForm.taskList,
                id: currentData.value.id,
                priority: milepostState.modalForm.priority,
                labels: milepostState.modalForm.labels
            })
                .then(data => {
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    message.success(data.message)

                    cancleMbTask()

                    getData()
                })
                .finally(() => {
                    milepostState.okLoading = false
                })
        })
    }
    // 关闭模板任务新建
    function cancleMbTask() {
        milepostState.addOrEditVisible = false
        milepostState.current = 1
        milepostState.modalForm.functionAbbreviation = undefined
        milepostState.modalForm.templateTaskId = undefined
        milepostState.modalForm = {
            templateTaskId: [],
            projectId: useProjectId.value,
            functionAbbreviation: undefined,
            taskList: []
        }
    }
    const PromiseProxy = Promise
    function confirmDelete(id) {
        del(`/solution-ppm/api/v2/built-in-system-ppm/project/story/${id}`).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            getData()
        })
    }
    function useDebounce(fn: (...args: any[]) => void, delay = 500) {
        let timer: ReturnType<typeof setTimeout> | null = null

        return function (...args: any[]) {
            if (timer) clearTimeout(timer)
            timer = setTimeout(() => {
                fn(...args)
            }, delay)
        }
    }
    // 包一层防抖函数
    const debounceGetData = useDebounce(getData, 500)
    //     编辑story
    function handleEditStory(record) {
        console.log(record)
        const item = cloneDeep(record)
        Object.assign(milepostState.modalForm, item)
        milepostState.modalForm.timeRangeList = !item.startTime||!item.endTime?[]: [item.startTime, item.endTime]
        currentData.value = item
        milepostState.addOrEditVisible = true
        milepostState.addOrEditTitle = '编辑用户故事'
    }
    function getStatusList() {
        get('/solution-ppm/api/v2/built-in-system-ppm/dictionary/search/PTYHGS.RWZT').then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            milepostState.statusList = data.data.map(item => {
                return {
                    label: item.itemName,
                    value: item.itemCode
                }
            })
        })
    }
    function handlerGetSpace(data) {
        return data?.split(/[,;；]/)
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .content {
        position: relative;
        height: calc(100vh - 300px);
        overflow-y: auto;
    }
    .no-progress {
        height: 370px;
        width: 100%;
        background-color: #fff;
        display: flex;
        justify-content: center;
        border: 1px solid #fff;
        border-radius: 10px;
        position: relative;
        /* 水平居中 */
    }
    .no-progress .tip {
        width: 200px;
        height: 101px;
        background-image: url('http://10.40.0.33:9001/file-storage/404789380744112128.png');
        background-size: cover;
        position: absolute;
        top: 30%;
        color: rgb(89, 89, 89);
    }
    .no-progress .tip .message {
        position: absolute;
        left: 35%;
        bottom: -40px;
        font-size: 16px;
        color: rgb(89, 89, 89);
    }
    .form-model :deep(.ant3-form-item-label) {
        width: 110px;
    }
    .story-item {
        background: #ffffff;
        box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.2);
        border-radius: 4px;
        margin: 1px 1px 24px 1px;
    }
    .story-title {
        display: flex;
        justify-content: space-between;
        background: rgba(56, 117, 255, 0.1);
        border-radius: 4px 4px 0 0;
        padding: 17px 24px;
    }
    .title-left {
        display: flex;
        gap: 8px;
        font-size: 16px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 600;
        align-items: center;
    }
    .status-tag,
    .priority-tag {
        font-size: 14px;
        color: #ffffff;
        letter-spacing: 0;
        text-align: center;
        line-height: 22px;
        font-weight: 500;
        width: 55px;
        height: 22px;
        border-radius: 2px;
        text-align: center;
    }
    .priority-tag {
        background: #40a9ff;
        border-radius: 2px;
    }
    .story-content {
        padding: 16px 24px;
    }
    .one-line,
    .two-line {
        display: flex;
        gap: 24px;
        align-items: center;
    }
    .one-line {
        margin-bottom: 12px;
    }
    .row-item {
        flex: 1 1 calc((100% - 5 * 24px) / 6); /* 每行 6 项，5 个间距 */
        display: flex;
        flex-direction: row;
        min-width: 0;
    }
    .one-line .row-item:first-child,
    .two-line .row-item:first-child {
        flex: 0 0 auto; /* 内容自适应宽度，不参与均分 */
        max-width: 160px; /* 可选：防止特别长时撑开，视情况而定 */
    }

    .one-line .row-item:not(:first-child),
    .two-line .row-item:not(:first-child) {
        flex: 1; /* 剩下的元素平均分配 */
    }
    .item-title {
        white-space: nowrap;
        font-family: PingFangSC-Regular;
        font-size: 14px;
        color: #595959;
        letter-spacing: 0;
        text-align: right;
        font-weight: 400;
    }

    .item-content {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        cursor: default;
        font-family: PingFangSC-Medium;
        font-size: 14px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 600;
    }
    .item-icon {
        display: flex;
        flex-wrap: wrap;
        gap: 8px; /* 可选：让 tag 之间有间距 */
        margin-bottom: 16px;
    }
    .label-item {
        display: flex;
        background-color: #eeeeee;
        align-items: center;
        padding: 1px 8px;
        font-size: 14px;
        color: #595959;
        letter-spacing: 0;
        text-align: center;
        font-weight: 400;
        gap: 4px;
        border-radius: 2px;
    }
    .label-img {
        background-image: url('http://10.40.0.33:9001/file-storage/503656902913648640-source.png');
        background-size: cover;
        width: 10px;
        height: 10px;
    }
</style>
